package com.davidlife.javase.netsocket.simulatebs;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/*
访问：http://127.0.0.1:8888/webapp/index.html
注意：不同的浏览器，内核不一样，解析效果有可能不一样。
 */
public class BsServerHtml {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(8888);
        System.out.println("服务端启动，等待连接。。。");
        while (true) {
            Socket s = ss.accept();
            new Thread(new Web(s)).start();
        }
    }

    static class Web implements Runnable {
        Socket s;

        public Web(Socket s) {
            this.s = s;
        }

        @Override
        public void run() {
            try {
                BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
                //解析要请求的 HTML 页面路径
                String firstLine = br.readLine();
                String[] split = firstLine.split(" ");
                String path = split[1].substring(1);
                System.out.println(path);
                //if(BsServerHtml.class.getResource("/" + path) == null) return;

                String file = BsServerHtml.class.getResource("/" + path).getFile();
                System.out.println("file path: " + file);

                OutputStream out = s.getOutputStream();
                // 写入HTTP协议响应头,固定写法
                out.write("HTTP/1.1 200 OK\r\n".getBytes());
                out.write("Content-Type:text/html\r\n".getBytes());
                // 必须要写入空行,否则浏览器不解析
                out.write("\r\n".getBytes());

                FileInputStream fis = new FileInputStream(file);
                //一读一写复制文件,把服务读取的html文件回写到客户端
                int len = 0;
                byte[] bytes = new byte[1024];
                while((len = fis.read(bytes))!=-1){
                    out.write(bytes,0,len);
                }

                //释放资源
                br.close();
                fis.close();
                s.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
